﻿using System;
using System.Collections.Generic;
using System.Text;

using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.ComponentModel;
using System.Collections;
using System.IO;

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
namespace AUV5.Common
{
    public class PageBase : System.Web.UI.Page
    {
        public const string URL_INDEX = "/Pages/Index.aspx";
        public const string URL_LOGIN = "/Pages/Login.aspx";
        public const string MANAGER = "manager";

        public static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="txt"></param>
        /// <returns></returns>
        public string EncryptMD5(string txt)
        {
            return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(txt, "MD5");
        }
        /// <summary>
        /// 获取创建时间与当前时间的时间差，返回最大单位
        /// </summary>
        /// <param name="datetime"></param>
        /// <returns></returns>
        public string GetTimeSpan(DateTime datetime)
        {
            string resultStr = "";
            DateTime now = DateTime.Now;

            if (datetime < now)
            {
                //by amos 计算一个日期与当前日期的时间差
                TimeSpan ts = now.Subtract(datetime);

                if (ts.Days > 365)
                {
                    resultStr = string.Format("{0}年前", now.Year - datetime.Year);
                }
                else if (ts.Days > 31)
                {
                    resultStr = string.Format("{0}个月前", now.Month - datetime.Month + (now.Year - datetime.Year) * 12);
                }
                else if (ts.Days > 0)
                {
                    resultStr = string.Format("{0}天前", ts.Days);
                }
                else if (ts.Hours > 0)
                {
                    resultStr = string.Format("{0}小时前", ts.Hours);
                }
                else if (ts.Minutes > 0)
                {
                    resultStr = string.Format("{0}分钟前", ts.Minutes);
                }
                else
                {
                    resultStr = "刚刚";
                }
            }
            else
            {
                resultStr = "刚刚";
            }
            return resultStr;
        }
        /// <summary>
        /// 获取时间差，返回天数
        /// </summary>
        /// <param name="beginDate"></param>
        /// <returns></returns>
        public string GetDaySpan(DateTime beginDate)
        {
            if (beginDate < DateTime.Now)
            {
                TimeSpan ts = DateTime.Now - beginDate;
                return ts.Days.ToString();
            }
            else
            {
                return "0";
            }
        }

        public string CutString(string content, int bitlength)
        {
            byte[] bytes = System.Text.Encoding.Unicode.GetBytes(content);
            int n = 0;  //  表示当前的字节数
            int i = 0;  //  要截取的字节数
            for (; i < bytes.GetLength(0) && n < bitlength; i++)
            {

                //  偶数位置，如0、2、4等，为UCS2编码中两个字节的第一个字节
                if (i % 2 == 0)
                {
                    n++;      //  在UCS2第一个字节时n加1
                }
                else
                {
                    //  当UCS2编码的第二个字节大于0时，该UCS2字符为汉字，一个汉字算两个字节
                    if (bytes[i] > 0)
                    {
                        n++;
                    }
                }

            }

            //  如果i为奇数时，处理成偶数
            if (i % 2 == 1)
            {
                //  该UCS2字符是汉字时，去掉这个截一半的汉字 

                if (bytes[i] > 0)

                    i = i - 1;

                 //  该UCS2字符是字母或数字，则保留该字符
                else
                    i = i + 1;
            }
            return System.Text.Encoding.Unicode.GetString(bytes, 0, i);

        }


        /// <summary>
        /// 获取客户端mac地址（未验证）
        /// </summary>
        /// <returns></returns>
        protected string GetClinetMACAddress()
        {
            System.Management.ManagementClass class1 = new System.Management.ManagementClass("Win32_NetworkAdapterConfiguration");
            System.Management.ManagementObjectCollection collection1 = class1.GetInstances();
            int num1 = 0;
            StringBuilder builder1 = new StringBuilder();
            using (System.Management.ManagementObjectCollection.ManagementObjectEnumerator enumerator1 = collection1.GetEnumerator())
            {
                //while (enumerator1.MoveNext())
                //{
                //    System.Management.ManagementObject obj1 = enumerator1.Current as System.Management.ManagementObject;
                //    if ((bool)obj1.Get("IPEnabled"))
                //    {
                //        if (num1 > 0)
                //        {
                //            builder1.Append("|");
                //        }
                //        builder1.Append(obj1.Get("MacAddress").ToString());
                //        num1++;
                //    }
                //    obj1.Dispose();
                //}
            }

            return builder1.ToString();
        }

        #region 关于cookie

        /// <summary>
        /// 设置一个Cooke的键值
        /// </summary>
        /// <param name="CookieName">Cookie名称</param>
        /// <param name="KeyName">键</param>
        /// <param name="CookiesValue">值</param>
        public static void CreateCookiesByKeyName(string CookieName, string KeyName, string CookiesValue)
        {
            HttpCookie HC;
            if (System.Web.HttpContext.Current.Request.Cookies[CookieName] != null)
            {
                HC = HttpContext.Current.Request.Cookies[CookieName];
            }
            else
            {
                HC = new HttpCookie(CookieName);
            }

            HC.Values[KeyName] = CookiesValue;
            HC.Secure = false;
            //HC.Domain = "";
            HC.Expires = DateTime.Now.AddDays(7);
            System.Web.HttpContext.Current.Response.Cookies.Add(HC);
        }

        /// <summary>
        /// 返回Cookies的键值
        /// </summary>
        /// <param name="CookieName">Cookies名称</param>
        /// <param name="KeyName">键</param>
        /// <returns></returns>
        public static string GetCookiesByKeyName(string CookieName, string KeyName)
        {

            HttpCookie HC;
            if (System.Web.HttpContext.Current.Request.Cookies[CookieName] != null)
            {
                HC = HttpContext.Current.Request.Cookies[CookieName];
                HC.Secure = false;
                if (HC.Values[KeyName] != null)
                {
                    string a = HC.Values[KeyName].ToString();
                    return HC.Values[KeyName].ToString();
                }
                else
                {
                    return string.Empty;
                }

            }
            else
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// 根据键值Cookie
        /// </summary>
        /// <param name="CookieName"></param>
        public static void RemoveCookiesByKeyName(string CookieName)
        {
            System.Web.HttpCookie cookie = System.Web.HttpContext.Current.Request.Cookies[CookieName];

            if (cookie != null)
            {
                //cookie.Domain = "";
                cookie.Expires = DateTime.Now.AddDays(-1);

                //System.Web.HttpContext.Current.Response.Cookies.Remove(CookieName);
                System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
            }
        }

        /// <summary>
        /// 清除所有Cookie
        /// </summary>
        public static void RemoveCookies()
        {
            try
            {
                foreach (string cookiename in System.Web.HttpContext.Current.Request.Cookies.AllKeys)
                {
                    if (System.Web.HttpContext.Current.Request.Cookies[cookiename] != null)
                    {
                        System.Web.HttpContext.Current.Response.Cookies[cookiename].Expires = DateTime.Now.AddDays(-1);
                        System.Web.HttpContext.Current.Response.Cookies[cookiename].Domain = ".taiclub.com.cn";
                        System.Web.HttpContext.Current.Response.Cookies.Remove(cookiename);
                    }
                }

                System.Web.HttpContext.Current.Response.Cookies.Clear();
            }
            catch (Exception)
            {

                throw;
            }
        }

        #endregion

        #region##获取某个枚举的全部信息
        /// <summary>
        /// 获取某个枚举的全部信息
        /// 创建人：Porschev
        /// 创建时间：2011-7-19
        /// </summary>
        /// <typeparam name="T">枚举</typeparam>
        /// <returns>枚举的全部信息</returns>
        public static List<AUV5.Model.ReadEnum> GetEnumList<T>()
        {
            List<AUV5.Model.ReadEnum> list = new List<AUV5.Model.ReadEnum>();
            AUV5.Model.ReadEnum re = null;
            Type type = typeof(T);
            foreach (int enu in System.Enum.GetValues(typeof(T)))
            {
                re = new AUV5.Model.ReadEnum();
                re.Name = GetEnumDesc(type, enu);
                re.Value = enu;
                list.Add(re);
            }
            return list;
        }
        #endregion

        /// <summary>
        /// 将一个枚举常数的名称的字符串表示转换成等效的枚举对象值。
        /// 创建人：amos
        /// 创建时间：2011-11-03
        /// </summary>
        /// <param name="enumType">枚举类型</param>
        /// <param name="strType">枚举常数的名称的字符串</param>
        /// <returns>枚举对象值</returns>
        public static int GetEnumValueByType(Type enumType, string strType)
        {
            return (int)System.Enum.Parse(enumType, strType);
        }

        #region##获得Enum类型description
        /// <summary>
        /// 获得Enum类型description
        /// 创建人：Porschev
        /// 创建时间：2011-7-19
        /// </summary>
        /// <param name="enumType">枚举的类型</param>
        /// <param name="val">枚举值</param>
        /// <returns>string</returns>
        public static string GetEnumDesc(Type enumType, object val)
        {
            string enumvalue = System.Enum.GetName(enumType, val);
            if (string.IsNullOrEmpty(enumvalue))
            {
                return "";
            }
            System.Reflection.FieldInfo finfo = enumType.GetField(enumvalue);
            object[] enumAttr = finfo.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), true);
            if (enumAttr.Length > 0)
            {
                System.ComponentModel.DescriptionAttribute desc = enumAttr[0] as System.ComponentModel.DescriptionAttribute;
                if (desc != null)
                {
                    return desc.Description;
                }
            }
            return enumvalue;
        }
        #endregion

        /// <summary>
        /// 获取网站地址
        /// </summary>
        /// <returns></returns>
        public string GetHostAddress()
        {
            return "http://" + HttpContext.Current.Request.Url.Authority;
        }
    }
}
